<template>
  <div class="master-container">
    <el-card :style="{maxHeight: contentHeight * 0.9 + 'px'}" class="box-card">
      <div class="title">办理副卡</div>
      <!-- 建卡表单 -->
      <div class="card-form">
        <el-steps :active="1" finish-status="success" simple style="margin-bottom: 20px;">
          <el-step title="识别主卡"></el-step>
          <el-step title="识别副卡"></el-step>
          <el-step title="填写信息"></el-step>
          <el-step title="确认建卡"></el-step>
        </el-steps>
        <el-form ref="dataFormRef" :model="dataForm" :rules="formRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="主卡编号：" prop="masterCardNo">
                <el-input v-model="dataForm.masterCardNo" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align:center;">
              <el-tooltip content="读卡" placement="top">
                <el-button circle icon="el-icon-bank-card" type="success"
                           @click="readMasterCard"></el-button>
              </el-tooltip>
            </el-col>
            <el-col :span="12">
              <el-form-item label="副卡编号：" prop="cardNo">
                <el-input v-model="dataForm.cardNo" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="卡名称：" prop="cardName">
                <el-input v-model="dataForm.cardName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名：" prop="username">
                <el-input v-model="dataForm.username" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话：" prop="phone">
                <el-input v-model="dataForm.phone" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号：" prop="idCardNo">
                <el-input v-model="dataForm.idCardNo" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车牌号码：" prop="carNumber">
                <el-input v-model="dataForm.carNumber" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员码：" prop="openid">
                <el-input v-model="dataForm.openid" clearable type="password"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支付密码：" prop="password">
                <el-input v-model="dataForm.password" clearable type="password"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="确认密码：" prop="password2">
                <el-input v-model="dataForm.password2" clearable type="password"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="可用油品：">
                <el-checkbox-group v-model="usableFuelList">
                  <el-checkbox label="0#"></el-checkbox>
                  <el-checkbox label="92#"></el-checkbox>
                  <el-checkbox label="95#"></el-checkbox>
                  <el-checkbox label="98#"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="联系地址：" prop="address">
                <el-input v-model="dataForm.address" clearable maxlength="100" placeholder="请输入联系地址"
                          type="textarea"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 工具栏 -->
        <div class="btn-bar">
          <el-button icon="el-icon-s-open" round size="small" style="float:left;" type="primary" @click="initCard">
            卡初始化
          </el-button>
          <el-button round size="small" type="danger" @click="resetForm">重置表单</el-button>
          <el-button round size="small" type="primary" @click="doAddCard">立即开卡</el-button>
        </div>
      </div>
    </el-card>
    <div class="home-btn">
      <div class="btn-item">
        <el-button icon="el-icon-back" round size="small" type="primary" @click="goBackHome"> 返 回</el-button>
      </div>
      <div class="btn-item">
        <el-button icon="el-icon-search" round size="small" type="info" @click="goCardInfo">卡查询</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import {getStationList} from '@/api/baseInfo'
import {makeCardSecond} from '@/api/card'
import {initCard, isNewEmptyCard, readCardNo, writeCardNo} from '@/utils/cardreader'
import {getCardInfo} from '../../api/card'

export default {
  name: 'AddSecondCard',
  data () {
    var validatePass = (rule, value, callback) => {
      if (this.dataForm.password !== '') {
        // 6位数字密码
        var reg = new RegExp(/^\d{6}$/)
        if (reg.test(value)) {
          this.$refs.dataFormRef.validateField('password2')
        } else {
          callback(new Error('密码必须为6位数字'))
        }
      }
      callback()
    }
    var validatePass2 = (rule, value, callback) => {
      if (this.dataForm.password !== '') {
        if (value === '') {
          callback(new Error('请再次输入密码！'))
        } else if (value !== this.dataForm.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      dataForm: {
        masterCardNo: '', // 主卡编号
        cardNo: '', // 副卡编号
        cardName: '',
        username: '',
        phone: '',
        idCardNo: '',
        carNumber: '',
        openid: '',
        address: '',
        stationId: '',
        operator: '',
        cardType: 1,
        invoiceType: 1,
        password: '',
        password2: ''
      },
      stationList: [],
      formRules: {
        cardNo: {required: true, message: '副编号不能为空！', trigger: 'change'},
        masterCardNo: {required: true, message: '主卡编号不能为空！', trigger: 'change'},
        username: {required: true, message: '请输入用户姓名', trigger: 'change'},
        phone: {required: true, message: '请输入电话号码', trigger: 'change'},
        password: [{required: true, validator: validatePass, trigger: 'change'}],
        password2: [{required: true, validator: validatePass2, trigger: 'change'}]
      },
      usableFuelList: []
    }
  },
  computed: {
    ...mapGetters(['contentHeight', 'stationId', 'operator'])
  },
  mounted () {
    getStationList().then(res => {
      console.log(res)
      this.stationList = res.data
    }).catch(err => {
      console.log(err)
    })
  },
  methods: {
    goBackHome () {
      this.$router.push('/card')
    },
    goCardInfo () {
      this.$router.push('/card/info')
    },
    resetForm () {
      this.$refs['dataFormRef'].resetFields()
      this.usableFuelList = []
      this.$message.success('操作成功')
    },
    doAddCard () {
      this.dataForm.stationId = this.stationId
      this.dataForm.operator = this.operator
      this.dataForm.usableFuelNames = this.usableFuelList.join(',')
      console.log(this.dataForm)
      this.$refs['dataFormRef'].validate((valid) => {
        if (valid) {
          this.$confirm('开卡过程中不要移动读卡器上的卡片，否则会出现写卡失败！！！?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // if (!isNewCard(readCardNo())) {
            //   this.$message.warning('该卡不是空白卡！')
            //   return false
            // }
            makeCardSecond(this.dataForm).then(res => {
              console.log(res)
              this.$message.success(res.msg || '建卡成功！')
              const cardNoToWrite = res.data.cardNo
              // 执行写卡操作
              let flag = writeCardNo(cardNoToWrite)
              if (flag === 'success') {
                this.$message.success('写卡成功！')
                this.resetForm()
              }
            }).catch(err => {
              console.log(err)
              this.$message.error(err || '建卡出错！')
            })
          }).catch(() => {
            console.log('cancle')
          })
        }
      })
    },
    readMasterCard () {
      let cardNo = ''
      if (this.dataForm.masterCardNo) {
        cardNo = this.dataForm.masterCardNo
      } else {
        cardNo = readCardNo()
      }
      getCardInfo(cardNo).then(res => {
        console.log('查询的主卡信息')
        console.log(res)
        this.$message.success(res.msg || '查询成功')
        this.dataForm.phone = res.data.phone
        this.dataForm.cardName = res.data.cardName
        this.dataForm.masterCardNo = cardNo
      }).catch(err => {
        console.log(err)
        this.$message.error((err || '查询失败') + cardNo)
      })
    },
    initCard () {
      console.log('initCard')
      var err = isNewEmptyCard()
      if (err) {
        this.$message.warning('该卡不是有效的空白卡')
        return false
      }
      err = initCard()
      if (err) {
        this.$message.error('卡初始化失败')
        return false
      }
      this.$message.success('卡初始化成功！')
    }
  }
}
</script>

<style scoped>
.el-select {
  width: 100%;
}

.box-card {
  width: 60%;
  margin-left: 20%;
  position: absolute;
  top: 4%;
  overflow-y: auto;
}

.home-btn {
  position: absolute;
  top: 2%;
  left: 2%;
}

.btn-item {
  margin-bottom: 20px;
}

.title {
  text-align: center;
  padding-top: 1%;
  font-size: 1.6rem;
  color: #666;
}

.card-form {
  background: white;
  padding: 20px;
}

.btn-bar {
  text-align: right;
}
</style>